/*
 *      proc_view.cpp
 *      
 *      Copyright 2009 AzureSky <AzureSky.fedora@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

#include "proc_view.h"

proc_view::proc_view(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade):
	Gtk::TreeView(cobject),
	refXml(refGlade)
{
	my_uid = getuid();
	
	init_view();
	proc_title();
	proc_read();
}

proc_view::~proc_view()
{
}

void proc_view::init_view()
{
	p_proc_model = Gtk::ListStore::create(proc_list);
	set_model(p_proc_model);
}

void proc_view::proc_title()
{
  	append_column ("进程名", proc_list.m_comm);
	append_column ("状态", proc_list.m_stat);
	append_column_numeric ("PID", proc_list.m_pid,"%d");
	append_column_numeric ("UID", proc_list.m_uid,"%d");
	append_column_numeric ("内存 /KB", proc_list.m_mem,"%d");
}

void proc_view::proc_read()
{
	the_list.refresh();
	proc_list::iterator it;
	for(it = the_list.begin();it != the_list.end();++it){
		if(it->uid == my_uid)
			add_row(it);	}
}

void proc_view::proc_refresh()
{
		p_proc_model -> clear();
		proc_read();
}

std::string proc_view::char_to_state(char state)
{
	switch(state){
		case 'R':return "Running";break;
		case 'S':return "Sleeping";break;
		case 'D':return "Waiting";break;
		case 'Z':return "Zombie";break;
		case 'T':return "Stopped";break;
		case 'W':return "Paging";break;
		default : return "unknow";
	}
}

void proc_view::add_row(proc_list::iterator it)
{
    Gtk::TreeModel::Row row = *(p_proc_model -> append());
	row[proc_list.m_comm] = std::string(it->comm);
  	row[proc_list.m_stat] = char_to_state(it->state);
  	row[proc_list.m_pid] = it->pid;
  	row[proc_list.m_uid] = it->uid;
  	if(it->mem_use != -1)
		row[proc_list.m_mem] = it->mem_use;
	else
		row[proc_list.m_mem] = 0;
}
